<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/3/21
 * Time: 19:53
 */
namespace Modules\Service\Logic;

use App\Models\CompanyOilCard;
use App\Models\MobileRechargeOrder;
use App\Models\MobileRechargeOrderDetail;
use App\Models\MobileRechargeTask;
use App\Models\OilCard;
use App\Models\Pay;
use App\Models\Recharge;
use App\Models\RechargeOrder;
use App\Models\RechargeOrderDetail;
use App\Models\RechargeTask;
use App\Models\ShopOrder;
use App\Models\User;
use App\Models\UserCoupon;
use function foo\func;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RechargeLogic extends BaseLogic{

/*    //充值支付
    public static function oilOrderAndPay($oilCardId,$openid,$rechargeId,$payType,$rechargeAmount,$couponId,$userData){
        try {
            DB::beginTransaction();
            //查询油卡数据
            $oilCardData = OilCard::find($oilCardId);
            if (!$oilCardData) return self::fail(1012, "油卡不存在");
            //如果openid存在,则修改用户openid
            if ($openid) {
                User::where("id", $userData->id)->update(["open_id" => $openid]);
            }
            //格式化钱符号
            $rechargeAmount = formatPrice($rechargeAmount);
            //卡号
            $card_no = $oilCardData->card_no;
            //油卡类型
            $card_type = $oilCardData->type;
            //定义参数
            $discount = '';
            $months = '';
            $type = 2;
            //查询充值套餐
            if ($rechargeId) {
                //查询套餐
                $rechargeData = Recharge::find($rechargeId);
                if (!$rechargeData) return self::fail(1013, "充值套餐不存在");
                //赋值
                $discount = $rechargeData->discount;
                $months = $rechargeData->months;
                $type = 1;
                //计算套餐价格
                $rechargeAmount = formatPrice(($rechargeAmount * $rechargeData->months) * $rechargeData->discount);
            }
            //查询优惠券信息
            if ($couponId) {
                $couponData = UserCoupon::find($couponId);
                if (!$couponData) return fail(1016, "无效的优惠券,请重新选择");
                //查询用户充值记录
                $rechargeRecords = RechargeOrder::where("user_id", $userData->id)->first();
                if ($rechargeRecords) {
                    //判断是否为新人专享优惠券
                    if ($couponData->new_exclusive == 1) {
                        return fail(1017, "优惠券为新人专享,请重新选择");
                    }
                }
                //计算价格
                $rechargeAmount = $rechargeAmount - $couponData->amount;
                $rechargeAmount = $rechargeAmount < 0 ? 0 : $rechargeAmount;
            }

            //实例化对象
            $order = new RechargeOrder();
            $order->user_id = $userData->id;
            $order->recharge_id = $rechargeId;
            $order->coupon_id = $couponId;
            $order->type = $type;
            $order->recharge_amount = $rechargeAmount;
            $order->oil_card_id = $oilCardId;
            $order->discount = $discount;
            $order->months = $months;
            $order->user_mobile = $userData->mobile;
            $order->card_type = $card_type;
            $order->card_no = $card_no;
            $order->status = 0;
            $order->created_at = Carbon::now();
            Log::info("order",$order);
            //创建支付
            $pay = new Pay();
            $pay->payment_method = $payType;
            $pay->user_id = $userData->id;
            $pay->pay_sn = Pay::makeYouKaPaySN();
            $pay->amount = $rechargeAmount;
            $pay->save();

            $order->pay_id = $pay->id;//支付流水id
            $order->save();
            Log::info("order",$order);

            $response = [
                'order_id' => $order->id,
                'payment_method' => $payType,
                'pay_info' => null,
            ];
            Log::info("json",$response);
            $response['pay_info'] = '';
            $response['weixin_app'] = null;
            if ($payType == 'alipay') {
                $response['pay_info'] = Pay::alipay($pay);
            }
            if ($payType == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp($pay);
            }
            if ($payType == 'weixin') {
                $response['weixin'] = Pay::weixin($pay, $openid);
            }

            DB::commit();
            return success($response);
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return fail(500,"系统错误");
        }
    }

    //订单再次支付
    public static function oilOrderAgainPay($id,$payType,$openid){
        try {
            //查询订单
            $order = RechargeOrder::find($id);
            //查询用户信息
            $user = User::find(Token::data('id'));
            Log::error($user->id);
            //更改支付方式
            $pay = $order->pay;
            $pay->payment_method = $payType;
            $pay->save();

            $response = [
                'order_id' => $order->id,
                'payment_method' => $payType,
                'pay_info' => null,
            ];
            //支付序号
            if ($pay->pay_sn) {
                $pay->pay_sn = Pay::makeYouKaPaySN();
            }
            $response['pay_info'] = '';
            $response['weixin_app'] = null;
            if ($payType == 'alipay') {
                $response['pay_info'] = Pay::alipay_num($pay);
            }
            if ($payType == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp_num($pay);
            }
            if ($payType == 'weixin') {
                $response['weixin'] = Pay::weixin_num($pay, $openid);
            }
            return success($response);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }*/

    //订单列表
    public static function rechargeOrderLit($userId,$type,$page,$size,$status){
        try{
            //查询用户
            $userData = User::find($userId);
            if (!$userData)return fail(1014,"用户不存在");
            //查询全部订单
            if ($type=='oil_recharge'){
                if ($status=='all') {
                    $orderCount = RechargeOrder::where('user_id',$userId)->where('status','>',-2)->count();
                    $orderData = RechargeOrder::where('user_id', $userId)->where('status','>',-2)->forPage($page, $size)->orderBy('id', 'desc')->select('id','type','recharge_amount','months','status','order_sn','created_at')->get();
                }else{
                    if ($status==1){
                        $orderCount = RechargeOrder::where('user_id', $userId)->where(function ($query)use($status){
                            $query->where("status",1)->orWhere('status',2);
                        })->count();
                        $orderData = RechargeOrder::where('user_id', $userId)->where(function ($query)use($status){
                            $query->where("status",1)->orWhere('status',2);
                        })->forPage($page, $size)->orderBy('id', 'desc')->select('id', 'type','recharge_amount', 'months', 'status', 'order_sn', 'created_at')->get();
                    }else {
                        $orderCount = RechargeOrder::where('user_id', $userId)->where("status", $status)->count();
                        $orderData = RechargeOrder::where('user_id', $userId)->where("status", $status)->forPage($page, $size)->orderBy('id', 'desc')->select('id','type', 'recharge_amount', 'months', 'status', 'order_sn', 'created_at')->get();
                    }
                }
            }else{
                if ($status=='all') {
                    $orderCount = MobileRechargeOrder::where('user_id',$userId)->where('status','>',-2)->count();
                    $orderData = MobileRechargeOrder::where('user_id', $userId)->where('status','>',-2)->forPage($page, $size)->orderBy('id', 'desc')->select('id','type','recharge_amount','months','status','order_sn','created_at')->get();
                }else{
                    if ($status==1){
                        $orderCount = MobileRechargeOrder::where('user_id',$userId)->where(function ($query)use($status){
                            $query->where("status",1)->orWhere('status',2);
                        })->count();
                        $orderData = MobileRechargeOrder::where('user_id', $userId)->where(function ($query)use($status){
                            $query->where("status",1)->orWhere('status',2);
                        })->forPage($page, $size)->orderBy('id', 'desc')->select('id','type','recharge_amount','months','status','order_sn','created_at')->get();
                    }else{
                        $orderCount = MobileRechargeOrder::where('user_id',$userId)->where("status",$status)->count();
                        $orderData = MobileRechargeOrder::where('user_id', $userId)->where("status",$status)->forPage($page, $size)->orderBy('id', 'desc')->select('id','type','recharge_amount','months','status','order_sn','created_at')->get();
                    }
                }
            }
            $orderArray = [];
            if ($orderData->count()>0){
                foreach ($orderData as $item){
                    $status_text = '';
                    if ($item['status']==-1){
                        $status_text = "已取消";
                    }elseif ($item['status']==0){
                        $status_text = "待支付";
                    }elseif ($item['status']==1){
                        $status_text = "进行中";
                    }elseif ($item['status']==2){
                        $status_text = "进行中";
                    }elseif ($item['status']==3){
                        $status_text = "已充值";
                    }elseif($item['status']==7){
                        $status_text = "已退款";
                    }
                    $order_time = date('Y-m-d H:i:s',strtotime($item['created_at']));
                    if ($item['type']==2){
                        if ($type=='oil_recharge') {
                            $title = (int)$item['recharge_amount'] . '元油卡直充';
                        }else{
                            $title = (int)$item['recharge_amount'] . '元话费直充';
                        }
                    }else{
                        if ($type=='oil_recharge') {
                            $title = $item['months'] . '个月油卡套餐充值';
                        }else{
                            $title = $item['months'] . '个月话费套餐充值';
                        }
                    }
                    $orderArray[] = [
                        'id'=>$item->id,
                        'title'=>$title,
                        'amount'=>$item['recharge_amount'],
                        'status'=>$item['status'],
                        'status_text'=>$status_text,
                        'order_time'=>$order_time
                    ];
                }
            }
            return success(['count'=>$orderCount,'data'=>$orderArray]);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    //充值订单详情
    public static function recgargeOrderDetail($orderId,$type){
        try{
            //查询订单
            if ($type=='oil_recharge'){
                $orderData = RechargeOrder::where("id",$orderId)->select('id','recharge_amount','recharge_id','coupon_id','card_no','card_type','pay_amount','months','order_sn','created_at','status','shop_order_id')->first();
            }else{
                $orderData = MobileRechargeOrder::where("id",$orderId)->select('id','recharge_amount','mobile','recharge_id','coupon_id','pay_amount','months','order_sn','created_at','status')->first();
            }
            $coupon_text = '';
            if ($orderData->coupon_id != 0 && $orderData->coupon_id != '') {
                //查询优惠券
                $couponData = UserCoupon::find($orderData->coupon_id);
                if ($couponData)
                    $coupon_text = $couponData->title;
            } else {
                $coupon_text = "未使用优惠券";
            }

            $status_text = '';
            if ($orderData->stauts==-1){
                $status_text = "已取消";
            }elseif ($orderData->stauts==0){
                $status_text = "待支付";
            }elseif ($orderData->stauts==1){
                $status_text = "已支付";
            }elseif ($orderData->stauts==2){
                $status_text = "待充值";
            }elseif ($orderData->stauts==3){
                $status_text = "已充值";
            }elseif($orderData->status==7){
                $status_text = "已退款";
            }
            $order_time = date('Y-m-d H:i:s',strtotime($orderData->created_at));
            if ($orderData->recharge_id==0){
                if ($type=='oil_recharge') {
                    $title = (int)$orderData->recharge_amount . '元油卡直充';
                }else{
                    $title = (int)$orderData->recharge_amount . '元话费直充';
                }
            }else{
                if ($type=='oil_recharge') {
                    $title = $orderData->months . '个月油卡套餐充值';
                }else{
                    $title = $orderData->months . '个月话费套餐充值';
                }
            }
            $rechargeArray = [];
            if ($orderData->recharge_id){
                //查询充值详情
                if ($type=='oil_recharge'){
                    $rechargeData = RechargeTask::where("recharge_order_id",$orderId)->get();
                }else{
                    $rechargeData = MobileRechargeTask::where("recharge_order_id",$orderId)->get();
                }
                if ($rechargeData->count()>0){
                    $i =1;
                    foreach ($rechargeData as $value){
//                        if ($value['status']==0){
//                            $status_text = '待充值';
//                        }elseif($value['status']==1){
//                            $status_text = '进行中';
//                        }elseif ($value['status']==9){
//                            $status_text = '已充值';
//                        }else{
//                            $status_text = '充值失败';
//                        }
                        $rechargeArray[] = ["pay_at"=>date('Y-m-d',strtotime($value['pay_at'])),"amount"=>$value['amount'],"month"=>($i.'/'.$orderData->months),"status"=>$status_text];
                        $i++;
                    }
                }
            }
            if ($type=='oil_recharge') {
                if ($orderData->card_type==1){
                    $cardTypeName = '中石化';
                }else{
                    $cardTypeName = '中石油';
                }
                if ($type=='oil_recharge'){
                    if ($orderData->shop_order_id>0){
                        $orderType = "oil_card";
                    }else{
                        $orderType = "recharge";
                    }
                }else{
                    $orderType = "recharge";
                }
                $orderArray = ['id' => $orderData->id,"recharge_id"=>$orderData->recharge_id, "recharge_type"=>'oil_recharge','title' => $title, 'card_no'=>$orderData->card_no,"months"=>$orderData->months,'card_type'=>$orderData->card_type,'card_type_name'=>$cardTypeName,'status_text' => $status_text, 'amount' => $orderData->recharge_amount, 'coupon_text' => $coupon_text, 'pay_amount' => $orderData->pay_amount, 'order_sn' => $orderData->order_sn, 'order_time' => $order_time, "order_detail" => $rechargeArray, "status" => $orderData->status,"order_type"=>$orderType];
            }else{
                $orderArray = ['id' => $orderData->id,"recharge_id"=>$orderData->recharge_id,"recharge_type"=>'mobile_recharge', 'title' => $title, 'mobile'=>$orderData->mobile,"months"=>$orderData->months,'status_text' => $status_text, 'amount' => $orderData->recharge_amount, 'coupon_text' => $coupon_text, 'pay_amount' => $orderData->pay_amount, 'order_sn' => $orderData->order_sn, 'order_time' => $order_time, "order_detail" => $rechargeArray, "status" => $orderData->status,"order_type"=>"recharge"];
            }
            return success($orderArray);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //取消订单
    public static function rechargeOrderClose($orderId,$channel,$type){
        try{
            //查询订单
            if ($channel=='oil_recharge'){
                $orderData = RechargeOrder::find($orderId);
            }else{
                $orderData = MobileRechargeOrder::find($orderId);
            }
            if (!$orderData)return fail(1025,"订单不存在");
            if ($type=='close') {
                if ($orderData->status!=0)return fail(1027,"订单取消失败");
                $orderData->status = -1;
                $orderData->save();
                if ($channel=='oil_recharge'){
                    //绑定油卡
                    $shopOrder = ShopOrder::query()->where("order_sn",$orderData->order_sn)->where("order_type","oil_card")->first();
                    if ($shopOrder){
                        //查询油卡
                        $oilCardData = OilCard::query()->where("id",$orderData->oil_card_id)->where("status",0)->first();
                        if ($oilCardData){
                            $companyOilCardData = CompanyOilCard::query()->where("card_no",$oilCardData->card_no)->where("status",1)->first();
                            if ($companyOilCardData){
                                $companyOilCardData->status = 0;
                                $companyOilCardData->used_at = (NULL);
                                $companyOilCardData->user_id = 0;
                                $companyOilCardData->save();
                                $oilCardData->delete();
                            }
                        }
                    }
                }
            }else{
               $orderData->status = -2;
               $orderData->save();
            }

            if ($orderData->coupon_id){
                $coupon = UserCoupon::find($orderData->coupon_id);
                if($coupon->status == 4) {
                    $coupon->status = 1;
                    $coupon->save();
                }
            }

            return success();
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }
}